package com.ph.irp.base.accountbookType.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.ph.irp.base.accountbookType.dao.PBaseAccountbooktypeDAO;
import com.ph.irp.model.PBaseAccountbooktype;
import com.ph.util.DBUtil;

public class PBaseAccountbooktypeDAOImpl implements PBaseAccountbooktypeDAO {
	private ComboPooledDataSource dataSource ;
	
	public void setDataSource(ComboPooledDataSource dataSource){
		
		this.dataSource =dataSource ;
	}
	
	/**
	 * get the accountbook you need 
	 */
	@Override
	public PBaseAccountbooktype getAccountbooktype(int id) throws Throwable{
		// TODO Auto-generated method stub
		
		//create a PBaseAccountbooktype object
		PBaseAccountbooktype type = new PBaseAccountbooktype() ;
		
		//connection to database ,to create Statement for us
		Connection connection = null ;
		
		//Statement created by connection to execute the SQL
		PreparedStatement preparedStatement = null ;
		
		//Store the results we get from the database 
		ResultSet resultSet = null ;
		
		try {
			//从数据源获得数据库连接
			connection = dataSource.getConnection() ;
			
			//构建SQL语句
			StringBuilder sqlBuilder = new StringBuilder() ;		
			sqlBuilder.append("select a.typeName,a.typeCode from p_base_accountbookType a where a.typeId=?") ;		
			//由连接创建预备语句，执行查询
			preparedStatement = connection.prepareStatement(sqlBuilder.toString()) ;
			preparedStatement.setInt(1, id) ;
			resultSet = preparedStatement.executeQuery() ;
			//将结果集中的数据封装到会计科目类别type中
			resultSet.next();
			type.setTypeName(resultSet.getString("typeName")) ;
			type.setTypeCode(resultSet.getString("typeCode")) ;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new Exception(e.getMessage());
		}finally{		
			try {
				DBUtil.setNullObject(connection, preparedStatement,resultSet) ;
			} catch (RuntimeException ex) {
				// TODO Auto-generated catch block
				throw new Exception(ex.getMessage());
			}
			
		}
		
		return type;
	}

}
